<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Award
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();

        // item list
        $this->items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        // 报单区才有奖
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
            $this->recommend();
            $this->goSell();
        }

        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT'])) {
            // $this->diff();

            // 复购奖和常规不一样, 这里重新写的
            // 只返一层
            $this->diff_new();
            $this->goSell();
        }
    }

    // 分红
    protected function goSell()
    {
        // 销售分红 (每笔订单进来, 都需要处理整个推荐人关系链)
        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ], true);
        foreach ($chain as $item) {
            $this->sell($item);
        }
    }

    // 获取差价
    // (低级 - 高级 )价格 * 盒数 * 数量
    private function getDiffPrice($high_key, $low_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            $set = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $unit = Product::find()
                ->where(['id' => $item->product_id])
                ->select(['unit'])
                ->scalar();
            if ($unit == 0) {
                $unit = 1;
            }
            $sum += ($set[$low_key] - $set[$high_key]) * $unit * $item['quantity'];
        }

        return $sum;
    }

    // 获取平级奖, 低推高
    private function getEqualOrLow($key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            $set = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $unit = Product::find()
                ->where(['id' => $item->product_id])
                ->select(['unit'])
                ->scalar();
            if ($unit == 0) {
                $unit = 1;
            }
            $sum += ($set[$key]) * $unit * $item['quantity'];
        }

        return $sum;
    }

    protected function diff_new()
    {
        $referrer = Chain::getReferrer($this->user->id, true);
        if ($referrer) {

            $diff_amount = 0;
            $equal_amount = 0;
            $low_amount = 0;

            // 会员复购
            if ($this->user->level == UserLevel::$keys['vip1']) {
                // 只有差价奖
                if ($referrer->level == UserLevel::$keys['vip2']) {
                    $diff_amount = $this->getDiffPrice('diff_vip2', 'diff_vip1');
                }
                if ($referrer->level == UserLevel::$keys['vip3']) {
                    $diff_amount = $this->getDiffPrice('diff_vip3', 'diff_vip1');
                }
                if ($referrer->level == UserLevel::$keys['vip4']) {
                    $diff_amount = $this->getDiffPrice('diff_vip4', 'diff_vip1');
                }
            }

            // 区代复购
            if ($this->user->level == UserLevel::$keys['vip2']) {
                // 差价
                if ($referrer->level == UserLevel::$keys['vip3']) {
                    $diff_amount = $this->getDiffPrice('diff_vip3', 'diff_vip2');
                }
                if ($referrer->level == UserLevel::$keys['vip4']) {
                    $diff_amount = $this->getDiffPrice('diff_vip4', 'diff_vip2');
                }

                // 平级
                if ($referrer->level == UserLevel::$keys['vip2']) {
                    $equal_amount = $this->getEqualOrLow('equal');
                }

                // 低推高
                if ($referrer->level == UserLevel::$keys['vip1']) {
                    $equal_amount = $this->getEqualOrLow('low');
                }
            }

            // 市代复购
            if ($this->user->level == UserLevel::$keys['vip3']) {
                // 差价
                if ($referrer->level == UserLevel::$keys['vip4']) {
                    $diff_amount = $this->getDiffPrice('diff_vip4', 'diff_vip3');
                }

                // 平级
                if ($referrer->level == UserLevel::$keys['vip3']) {
                    $equal_amount = $this->getEqualOrLow('equal');
                }

                // 低推高
                if ($referrer->level == UserLevel::$keys['vip1'] || $referrer->level == UserLevel::$keys['vip2']) {
                    $equal_amount = $this->getEqualOrLow('low');
                }
            }

            if ($this->user->level == UserLevel::$keys['vip4']) {
                // 平级
                if ($referrer->level == UserLevel::$keys['vip4']) {
                    $equal_amount = $this->getEqualOrLow('equal');
                }

                // 低推高
                if ($referrer->level == UserLevel::$keys['vip1'] || $referrer->level == UserLevel::$keys['vip2'] || $referrer->level == UserLevel::$keys['vip3']) {
                    $equal_amount = $this->getEqualOrLow('low');
                }

                // var_dump($equal_amount);exit;
            }

            if ($diff_amount > 0) {
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id,
                    $diff_amount, '21', '复购差价');
            }
            if ($equal_amount > 0) {
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id,
                    $equal_amount, '22', '复购平级奖');
            }
            if ($low_amount > 0) {
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id,
                    $low_amount, '23', '复购低推高');
            }


        }
    }

    // 复购差价然
    protected function diff()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [], true);

        $award_name = '复购差价';
        $award_type = 12;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;
        $diff_vip4 = 0;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;
        $has_vip4 = false;

        foreach ($chain as $user) {
            if ($user->level <= $this->user->level) {
                continue;
            }

            // 去掉会员
            if ($user->level == UserLevel::$keys['vip1']) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diff('diff_vip1');
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('diff_vip2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diff('diff_vip3');
                $diff_vip3 -= $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
            }
            if (!$has_vip4 && $user->level == UserLevel::$keys['vip4']) {
                $diff_vip4 = $this->_diff('diff_vip4');
                $diff_vip4 -= $diff_vip3 + $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip4, $award_type, $award_name);
                $has_vip4 = true;
                break;
            }
        }
    }

    private function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            // 这里可以不用商品原价, order_item中是折后价
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            // var_dump($product);exit;
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 推荐奖
    protected function recommend()
    {
        $total_price = $this->order->total_pay - $this->order->total_freight;
        $amount = 0;

        $referrer = Chain::getReferrer($this->user->id, true);
        if ($referrer) {

            // 区代
            if ($referrer->level == UserLevel::$keys['vip2']) {
                if ($total_price == $this->set->vip1) {
                    $amount = $this->set->vip2_vip1;
                }
                if ($total_price == $this->set->vip2) {
                    $amount = $this->set->vip2_vip2;
                }
                if ($total_price == $this->set->vip3) {
                    $amount = $this->set->vip2_vip3;
                }
                if ($total_price == $this->set->vip4) {
                    $amount = $this->set->vip2_vip4;
                }
            }

            // 市代
            if ($referrer->level == UserLevel::$keys['vip3']) {
                if ($total_price == $this->set->vip1) {
                    $amount = $this->set->vip3_vip1;
                }
                if ($total_price == $this->set->vip2) {
                    $amount = $this->set->vip3_vip2;
                }
                if ($total_price == $this->set->vip3) {
                    $amount = $this->set->vip3_vip3;
                }
                if ($total_price == $this->set->vip4) {
                    $amount = $this->set->vip3_vip4;
                }
            }

            // 省代
            if ($referrer->level == UserLevel::$keys['vip4']) {
                if ($total_price == $this->set->vip1) {
                    $amount = $this->set->vip4_vip1;
                }
                if ($total_price == $this->set->vip2) {
                    $amount = $this->set->vip4_vip2;
                }
                if ($total_price == $this->set->vip3) {
                    $amount = $this->set->vip4_vip3;
                }
                if ($total_price == $this->set->vip4) {
                    $amount = $this->set->vip4_vip4;
                }
            }

            $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id,
                $amount, '11', '推荐奖');


        }


    }

    // 销售分红奖
    protected function sell(User $referrer)
    {
        // var_dump($referrer);exit;

        // 直推多少个区代+
        $children = User::find()
            ->where(['referrer_id' => $referrer->id])
            ->andWhere(['level' => [
                UserLevel::$keys['vip2'],
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4']
            ]])
            ->select(['id'])
            ->column();

        // 小于5个, 则不返
        if (count($children) < $this->set->sell_vip) {
            return;
        }

        // var_dump($referrer);exit;


        // 推荐人业绩
        $unit = $this->getUnit($referrer->id);

        // var_dump($referrer->id, $unit);exit;

        foreach ($children as $id) {

            // var_dump($this->set->sell_num * $unit / 100, $unit);exit;

            // 如果团队中存在大于50%业绩的人, 则不算
            $u = $this->getUnit($id);
            if ($u >= $this->set->sell_num * $unit / 100) {
                $unit -= $u;
            }
        }

        // 去掉已返的
        // $unit = $this->subUnit($referrer, $unit);
        //
        // $amount = 0;
        // if ($unit >= $this->set->sell_4) {
        //     $amount = $this->set->sell_4_amount;
        //     $referrer->sell_4 = $referrer->sell_4 + 1;
        // } else if ($unit >= $this->set->sell_3) {
        //     $amount = $this->set->sell_3_amount;
        //     $referrer->sell_3 = $referrer->sell_3 + 1;
        // } else if ($unit >= $this->set->sell_2) {
        //     $amount = $this->set->sell_2_amount;
        //     $referrer->sell_2 = $referrer->sell_2 + 1;
        // } else if ($unit >= $this->set->sell_1) {
        //     $amount = $this->set->sell_1_amount;
        //     $referrer->sell_1 = $referrer->sell_1 + 1;
        // }

        // var_dump($unit);exit;

        // 改成只返一次了
        $amount = 0;

        if ($unit >= $this->set->sell_1 && $referrer->sell_1 <= 0) {
            $amount = $this->set->sell_1_amount;
            $referrer->sell_1 = $referrer->sell_1 + 1;
        } else if ($unit >= $this->set->sell_2 && $referrer->sell_2 <= 0) {
            $amount = $this->set->sell_2_amount;
            $referrer->sell_2 = $referrer->sell_2 + 1;
        } else if ($unit >= $this->set->sell_3 && $referrer->sell_3 <= 0) {
            $amount = $this->set->sell_3_amount;
            $referrer->sell_3 = $referrer->sell_3 + 1;
        } else if ($unit >= $this->set->sell_4 && $referrer->sell_4 <= 0) {
            $amount = $this->set->sell_4_amount;
            $referrer->sell_4 = $referrer->sell_4 + 1;
        }

        if ($amount > 0) {
            $referrer->save();
            $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id,
                $amount, '30', '分红');
        }
    }

    // 判断销售分红
    private function subUnit(User $user, $unit)
    {
        $sell4 = $user->sell_4 * $this->set->sell_4;
        $sell3 = $user->sell_3 * $this->set->sell_3;
        $sell2 = $user->sell_2 * $this->set->sell_2;
        $sell1 = $user->sell_1 * $this->set->sell_1;

        $total = $unit - $sell4 - $sell3 - $sell2 - $sell1;

        // var_dump($total);exit;

        if ($total < 0) {
            $total = 0;
        }

        return $total;
    }

    // 业绩 (多少套), 团队业绩
    private function getUnit($user_id)
    {
        $ids = Chain::getChildrenAllQuick($user_id, [
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ], ['id']);
        $ids = ArrayHelper::getColumn($ids, 'id');
        $ids = array_merge([$user_id], $ids);

        // var_dump($ids);exit;

        $orders = Order::find()
            ->where(['user_id' => $ids])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->with(['item.product'])
            ->select(['id'])
            ->asArray()
            ->all();

        // var_dump($orders);exit;

        // 计算产品套数
        $sum = 0;
        foreach ($orders as $order) {
            foreach ($order['item'] as $item) {
                $box = $item['product']['unit'];
                $sum += $box * $item['quantity'];
            }
        }

        return $sum;
    }

    // 保存佣金
    protected function saveCommission($user_id, $fans_id, $order_id, $balance, $type, $name)
    {
        if ($balance > 0) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {

                // balance logs
                UserBalance::addLog($user_id,
                    $account->balance, $balance, $account->balance + $balance, '返佣', $this->order->id);


                $account->balance += $balance;
                $account->save();
            }
        }
    }
}